package ThreadPoolDemo.读写锁;

import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockTest {

	public static void main(String[] args) {
		final Queue3 q3 = new Queue3();
		for (int i = 0; i < 3; i++) {
			new Thread() {
				public void run() {
					while (true) {
						q3.get();
					}
				}
			}.start();

			new Thread() {
				public void run() {
					while (true) {
						q3.put(new Random().nextInt(10000));
					}
				}
			}.start();
		}
	}
}

class Queue3 {
	private Object data = null;
	ReadWriteLock rwl = new ReentrantReadWriteLock();

	public void get() {
		rwl.readLock().lock();
		try {
			System.out.println(Thread.currentThread().getName() + "开始读");

			Thread.sleep((long) (Math.random() * 10000));
			System.out.println(Thread.currentThread().getName() + "读完了" + data);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {

			rwl.readLock().unlock();
		}

	}

	public void put(int nextInt) {
		rwl.writeLock().lock();
		try {
			System.out.println(Thread.currentThread().getName() + "开始写");
			Thread.sleep((long) (Math.random() * 10000));
			this.data = nextInt;
			System.out.println(Thread.currentThread().getName() + "写完了");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			rwl.writeLock().unlock();
		}

	}

}